import API from "../config/API";
import Service from '../service';
import { Op } from "sequelize";

export default function apiController(sourceName, router ){
    return router.get(API.BASIC_PATH+"/"+sourceName, async ctx => {
        const rlt  = await Service.list(sourceName,  ctx.query);
        const count  = await Service.count(sourceName,  ctx.query);
        ctx.set('Content-Range', `${sourceName} ${ctx.query.range[0]}-${ctx.query.range[1]}/319`);
        ctx.rest({
            data: rlt,
            total: count,
        })
    })
    .get(API.BASIC_PATH+"/"+sourceName+"/:id", async ctx => {
        const { id } = ctx.params;
        const rlt = await Service.one(sourceName, {
            where: {id}
        })
        ctx.rest({
            data: rlt,
        })
    })
    .put(API.BASIC_PATH+"/"+sourceName+"/:id", async ctx => {
        const { id } = ctx.params;
        try {
            const rlt = await Service.updateOne(
                sourceName, 
                {...JSON.parse(ctx.request.body), updatedAt: new Date()}, 
                {id}
            )
            
        } catch (error) {
            console.error(error);
            
        }
        
        const updateOne = await Service.one(sourceName, {
            where: {id}
        })
        ctx.rest({
            data: updateOne,
            code: sourceName+":update:success"
        })
    })
    .delete(API.BASIC_PATH+"/"+sourceName+"/:id", async ctx => {
        const { id } = ctx.params;
        await Service.delete(sourceName, {id});
        ctx.rest({
            data: {id},
            code: sourceName+":delete:success"
        })
        
    })
    .delete(API.BASIC_PATH+"/"+sourceName, async ctx => {
        const { filter } = ctx.query;
        const ids = JSON.parse(filter).id;
        const outIds = [];
        for (let i = 0; i < ids.length; i++) {
            const outId = ids[i];
            outIds.push({
                id: outId,
            })
        }
        await Service.delete(sourceName, {id: {[Op.in]: ids}});
        ctx.rest({
            data: outIds,
            code: sourceName+":delete:success"
        })
        
    })
    .post(API.BASIC_PATH+"/"+sourceName, async ctx => {
        const sourceParams = JSON.parse(ctx.request.body);
        const insertParams = {
            ...sourceParams,
            createdAt: new Date(),
            updatedAt: new Date()
        }
        const createOne = await Service.createOne(sourceName, insertParams);
        ctx.rest({
            data: createOne.dataValues,
            code: sourceName+":create:success"
        })
        
    })
}